<template>
  <div>
    <el-button type="primary" @click="showMapDialog">打开地图</el-button>
    <el-dialog :visible.sync="dialogVisible" width="80%" height="80%">
      <el-container style="height: 100%;">
        <el-aside width="300px" style="background-color: rgb(238, 241, 246)">
          <el-input placeholder="请输入目标地址" v-model="endAddress"></el-input>
          <el-button type="primary" @click="planRoute">规划路线</el-button>
        </el-aside>
        <el-main style="height: 100%;">
          <div id="mapContainer"></div>
        </el-main>
      </el-container>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'HotelSystemIndex',

  data () {
    return {
      dialogVisible: false,
      endAddress: '',
      map: null,
      startPoint: null,
      endPoint: null,
      route: null
    }
  },
  mounted () {
    this.initMap()
  },
  methods: {
    // 提交留言
    initMap() {
      AMapLoader.load({
        key: '09a3b5266284dd13cda2392545575657', // 设置您的key
        version: '2.0',
        plugins: ['AMap.PlaceSearch', 'AMap.Scale', 'AMap.ToolBar', 'AMap.Driving', 'AMap.CitySearch']
      }).then(AMap => {
        this.map = new AMap.Map('mapContainer', {
        zoom: 14
      })
      AMap.plugin('AMap.CitySearch', () => {
        const citySearch = new AMap.CitySearch()
        citySearch.getLocalCity((status, result) => {
          if (status === 'complete' && result.city) {
            this.startPoint = result.bounds.northeast
            console.log(this.startPoint)
          } else {
            this.$message.error('无法获取当前位置')
          }
        })
      })
    },
      })

    showMapDialog () {
      this.dialogVisible = true
    },
    planRoute () {
      const { endAddress } = this
      if (!endAddress) {
        this.$message.error('请输入目标地址')
        return
      }
      this.getEndLocation(endAddress)
    },
    getEndLocation (endAddress) {
      // 使用接口获取目标地址的经纬度
      const apiUrl = `https://restapi.amap.com/v3/geocode/geo?key=YOUR_KEY&address=${endAddress}`
      this.$http.get(apiUrl).then(response => {
        const location = response.data.geocodes[0].location.split(',')
        this.endPoint = [location[0], location[1]]
        this.drawRoute()
      }).catch(() => {
        this.$message.error('目标地址无法解析')
      })
    },
    drawRoute () {
      if (this.route) {
        this.route.clear()
      }
      AMap.plugin('AMap.Driving', () => {
        const driving = new AMap.Driving({
          map: this.map,
          panel: 'panel'
        })
        driving.search(this.startPoint, this.endPoint, (status, result) => {
          if (status === 'complete') {
            this.route = result.routes[0]
          } else {
            this.$message.error('路线规划失败')
          }
        })
      })
    }
  }

}
</script>

<style lang="less" scoped>

</style>
